package com.netty.timeold;

import java.nio.charset.StandardCharsets;
import java.util.Date;

import com.netty.timeold.model.BaseModel;
import com.netty.timeold.model.PingReq;
import com.sevenchildren.framework.entity.BiStringEntry;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class TimeServerSimpleHandler extends SimpleChannelInboundHandler<String> {

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}

	@Override
	protected void messageReceived(ChannelHandlerContext ctx, String body) throws Exception {
		System.out.print(ctx);
		System.out.println(" the time server recive order : [" + body.length() + "] " + body);
		if (PingReq.isPing(body)) {
			ByteBuf resp = Unpooled.copiedBuffer(body.getBytes(StandardCharsets.UTF_8));
			ctx.writeAndFlush(resp);
			return;
		}

		BiStringEntry bse = BaseModel.parse(body);
		String currentTime = bse.msg.startsWith("QUERY TIME ORDER") ? new Date(System.currentTimeMillis()).toString() : "BAD ORDER";
		currentTime = bse.code + " --- " + currentTime;
		ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes(StandardCharsets.UTF_8));
		ctx.writeAndFlush(resp);
	}
}
